#!/usr/bin/env python3
"""
用户邮箱系统 - 后端服务启动脚本
功能：启动FastAPI后端服务
端口：9999
自动重载：已开启
支持平台：Windows、Linux、macOS
"""

import subprocess
import sys
import os
import platform
from pathlib import Path

def get_python_executable():
    """获取当前Python解释器路径（跨平台）"""
    return sys.executable

def check_requirements():
    """检查必要的目录和文件"""
    project_dir = Path(__file__).parent.parent
    
    # 检查必要目录
    required_dirs = [
        project_dir / "emails",
        project_dir / "uploads" / "avatars",
        project_dir / "uploads" / "images",
        project_dir / "runtime" / "logs",
        project_dir / "runtime" / "cache",
        project_dir / "runtime" / "files"
    ]
    
    for dir_path in required_dirs:
        if not dir_path.exists():
            print(f"创建目录: {dir_path}")
            dir_path.mkdir(parents=True, exist_ok=True)
    
    # 检查数据库文件（在项目根目录）
    db_file = project_dir / "usermails.db"
    if not db_file.exists():
        print("提示: 数据库文件不存在，将在首次运行时自动创建")

def check_dependencies():
    """检查是否安装了必要的依赖"""
    try:
        import uvicorn
        import fastapi
        print("✓ 依赖检查通过")
        return True
    except ImportError as e:
        print(f"✗ 缺少必要依赖: {e}")
        print("\n请先安装依赖:")
        print(f"  {get_python_executable()} -m pip install -r api/requirements.txt")
        return False

def main():
    """启动FastAPI服务器"""
    system_info = f"{platform.system()} {platform.release()}"
    python_version = f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"
    
    print("=" * 60)
    print("用户邮箱系统 - 后端服务")
    print("=" * 60)
    print(f"系统平台: {system_info}")
    print(f"Python版本: {python_version}")
    print(f"Python路径: {get_python_executable()}")
    print(f"端口: 9999")
    print(f"自动重载: 已开启")
    print(f"API文档: http://localhost:9999/api/docs")
    print(f"健康检查: http://localhost:9999/api/health")
    print("=" * 60)
    
    # 设置工作目录为项目根目录
    project_dir = Path(__file__).parent.parent
    os.chdir(project_dir)
    
    # 检查必要的目录和文件
    check_requirements()
    
    # 检查依赖
    if not check_dependencies():
        sys.exit(1)
    
    # 设置PYTHONPATH以允许绝对导入
    env = os.environ.copy()
    pythonpath = str(project_dir)
    if 'PYTHONPATH' in env:
        pythonpath = pythonpath + os.pathsep + env['PYTHONPATH']
    env['PYTHONPATH'] = pythonpath
    
    # 使用当前Python解释器启动uvicorn服务器
    python_exe = get_python_executable()
    
    # 自动检测系统资源
    import multiprocessing
    cpu_count = multiprocessing.cpu_count()
    
    # 获取系统内存（GB）
    try:
        with open('/proc/meminfo', 'r') as f:
            mem_total = int(f.readline().split()[1]) / 1024 / 1024  # 转换为GB
    except:
        mem_total = 2  # 默认假设4GB
    
    # 保守配置：小型服务不需要太多worker
    # 低配服务器（≤2核或≤3GB内存）
    if cpu_count <= 2 or mem_total <= 3:
        workers = 2
        limit_concurrency = 100
        limit_max_requests = 1000
        timeout_keep_alive = 3
        backlog = 512
        server_type = "小型"
    # 中配服务器（3-8核，3-16GB内存）
    elif cpu_count <= 8 or mem_total <= 16:
        workers = 4
        limit_concurrency = 300
        limit_max_requests = 5000
        timeout_keep_alive = 5
        backlog = 1024
        server_type = "中型"
    # 高配服务器（>8核，>16GB内存）- 使用保守配置
    else:
        workers = 8  # 固定8个worker，适合小型服务
        limit_concurrency = 500
        limit_max_requests = 10000
        timeout_keep_alive = 5
        backlog = 2048
        server_type = "大型"
    
    # 环境变量可覆盖自动配置（高级用户）
    workers = int(env.get('WORKERS', workers))
    limit_concurrency = int(env.get('LIMIT_CONCURRENCY', limit_concurrency))
    limit_max_requests = int(env.get('LIMIT_MAX_REQUESTS', limit_max_requests))
    timeout_keep_alive = int(env.get('TIMEOUT_KEEP_ALIVE', timeout_keep_alive))
    backlog = int(env.get('BACKLOG', backlog))
    
    # 检查是否为开发模式
    is_dev_mode = env.get('DEV_MODE', '').lower() in ('true', '1', 'yes')
    
    if is_dev_mode:
        # 开发模式：单进程+热重载
        cmd = [
            python_exe, "-m", "uvicorn",
            "api.main:app",
            "--host", "0.0.0.0",
            "--port", "9999",
        ]
        print(f"\n⚠️  开发模式")
        print(f"✓ 热重载已启用")
    else:
        # 生产模式：多进程优化
        cmd = [
            python_exe, "-m", "uvicorn",
            "api.main:app",
            "--host", "0.0.0.0",
            "--port", "9999",
            "--workers", str(workers),
            "--limit-concurrency", str(limit_concurrency),
            "--limit-max-requests", str(limit_max_requests),
            "--timeout-keep-alive", str(timeout_keep_alive),
            "--backlog", str(backlog),
            "--reload",
            "--reload-dir", str(project_dir / "api"),
            "--log-level", "info"
        ]
        print(f"\n✓ 生产模式 [{server_type}]")
        print(f"✓ 系统资源: {cpu_count}核心 / {mem_total:.1f}GB内存")
        print(f"✓ Worker进程: {workers}")
        print(f"✓ 并发连接: {limit_concurrency}")
        print(f"✓ 请求限制: {limit_max_requests}")
        print(f"✓ Keep-Alive: {timeout_keep_alive}秒")
    
    print(f"\n正在启动服务...")
    print(f"命令: {' '.join(cmd)}\n")
    
    try:
        subprocess.run(cmd, check=True, env=env)
    except subprocess.CalledProcessError as e:
        print(f"\n错误: 服务器启动失败 - {e}")
        sys.exit(1)
    except KeyboardInterrupt:
        print("\n\n服务器已停止")
        sys.exit(0)
    except Exception as e:
        print(f"\n发生未预期的错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
